package com.moyv.schoolbbs.ui.adapter;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import com.moyv.schoolbbs.R;
import com.moyv.schoolbbs.base.Global;
import com.moyv.schoolbbs.pojo.Comment;
import com.moyv.schoolbbs.pojo.HandlerPosition;
import com.moyv.schoolbbs.pojo.Item;
import com.moyv.schoolbbs.pojo.Star;
import com.moyv.schoolbbs.service.CmtService;
import com.moyv.schoolbbs.service.StarService;
import com.moyv.schoolbbs.ui.config.CancelOrOkDialog;
import com.moyv.schoolbbs.ui.view.CommentsView;
import com.moyv.schoolbbs.ui.view.ExpandTextView;
import com.moyv.schoolbbs.ui.view.LikePopupWindow;
import com.moyv.schoolbbs.ui.view.OnPraiseOrCommentClickListener;
import com.moyv.schoolbbs.ui.view.PraiseListView;
import com.moyv.schoolbbs.util.KeyboardUtils;
import com.moyv.schoolbbs.util.ToastUtils;
import com.wang.avi.AVLoadingIndicatorView;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static android.content.ContentValues.TAG;
import static com.moyv.schoolbbs.config.AccountConstant.ACCOUNT;
import static com.moyv.schoolbbs.config.AccountConstant.LOGIN;
import static com.moyv.schoolbbs.config.AccountConstant.NAME;
import static com.moyv.schoolbbs.config.URLConstant.IMAGE_URL;
import static com.moyv.schoolbbs.service.DeletePostService.deletePost;
import static com.moyv.schoolbbs.util.FormatUtils.getFormatData;
import static com.moyv.schoolbbs.util.ToastUtils.show;
import static com.moyv.schoolbbs.util.UIHelper.closeDialog;

public class DataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    public Context context;
    private List<Item> postList;
    //评论框
    private EditText etComment;
    private LinearLayout llComment;
    private ViewHolder recyclerViewHolder;

    private int isLike = 0;
    private TextView tvSend;


    private String commentStr;
    //  type有两个值,区别主页显示和管理显示
    public static int MAIN = 202;
    public static int POSTMANAGER = 303;
    public static int STARAMNAGER = 404;
    public int type;


    // 普通布局
    private final int TYPE_ITEM = 1;
    // 脚布局
    private final int TYPE_FOOTER = 2;
    // 当前加载状态，默认为加载完成
    private int loadState = 2;
    // 正在加载
    public final int LOADING = 1;
    // 加载完成
    public final int LOADING_COMPLETE = 2;
    // 加载到底
    public final int LOADING_END = 3;

    //    防止重复加载
    List<Integer> positions = new ArrayList<>();

    public DataAdapter(Context context, List<Item> postList, LinearLayout llComment, EditText etComment, TextView tvSend) {
        this.context = context;
        this.postList = postList;
        this.etComment = etComment;
        this.llComment = llComment;
        this.tvSend = tvSend;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//        为每个Item inflater出一个View
        // 通过判断显示类型，来创建不同的View
        if (viewType == TYPE_ITEM) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_fragment_main, parent, false);
            return new ViewHolder(view);
        } else if (viewType == TYPE_FOOTER) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.loading_more, parent, false);
            return new FootViewHolder(view);
        } else {
            return null;
        }

    }

    @Override
    public int getItemCount() {
        return postList.size() + 1;
    }

    //    这个方法主要用于适配渲染数据到View中
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ViewHolder) {
            recyclerViewHolder = (ViewHolder) holder;
            isLike = postList.get(position).getMain().getStars().size();
            String name = postList.get(position).getMain().getUserInfo().getName();
            String introduction = postList.get(position).getMain().getUserInfo().getIntroduction() == null ? "" : postList.get(position).getMain().getUserInfo().getIntroduction();
            String Date = postList.get(position).getMain().getPost().getProTimer();
            String content = postList.get(position).getMain().getPost().getPostContent();
            recyclerViewHolder.tvUser.setText(name);
            recyclerViewHolder.tvIntro.setText(introduction);

            recyclerViewHolder.ivEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //评论弹框
                    Log.e(TAG, "onClick: " + position);
                    showLikePopupWindow(v, position, recyclerViewHolder);
                    tvSend.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            getComment(recyclerViewHolder, position);
                        }
                    });
                }
            });


//        判断是否有删除键
            if (type != MAIN) {
                recyclerViewHolder.tvDelete.setVisibility(View.VISIBLE);
                recyclerViewHolder.ivEdit.setVisibility(View.GONE);
                recyclerViewHolder.tvDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        removeData(position);
                    }
                });
            }

//        显示发表时间
            DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            java.util.Date date1 = null;
            try {
                date1 = fmt.parse(Date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Long date = date1.getTime();
            Long now = System.currentTimeMillis();
            String formatData = getFormatData(date, now);
            recyclerViewHolder.tvDate.setText(formatData);
//        帖子文字内容
            if (content.length() == 0) {
                recyclerViewHolder.expandTextView.setVisibility(View.GONE);
            } else {
                recyclerViewHolder.expandTextView.setVisibility(View.VISIBLE);
                recyclerViewHolder.expandTextView.setText(content);
            }
//            评论区显示判断
            if ((postList.get(position).getMain().getStars() != null && postList.get(position).getMain().getStars().size() > 0) && (postList.get(position).getMain().getComments() != null && postList.get(position).getMain().getComments().size() > 0)) {
                recyclerViewHolder.viewLike.setVisibility(View.VISIBLE);
            } else {
                recyclerViewHolder.viewLike.setVisibility(View.GONE);
            }
            if ((postList.get(position).getMain().getStars() != null && postList.get(position).getMain().getStars().size() > 0) || (postList.get(position).getMain().getComments() != null && postList.get(position).getMain().getComments().size() > 0)) {
                recyclerViewHolder.llLike.setVisibility(View.VISIBLE);
                if (postList.get(position).getMain().getStars() != null && postList.get(position).getMain().getStars().size() > 0) {
                    recyclerViewHolder.rvLike.setVisibility(View.VISIBLE);
                    recyclerViewHolder.rvLike.setDatas(postList.get(position).getMain().getStars());
                } else {
                    recyclerViewHolder.rvLike.setVisibility(View.GONE);
                }

                if (postList.get(position).getMain().getComments() != null && postList.get(position).getMain().getComments().size() > 0) {
                    recyclerViewHolder.rvComment.setVisibility(View.VISIBLE);
                    recyclerViewHolder.rvComment.setList(postList.get(position).getMain().getComments());
                    recyclerViewHolder.rvComment.setOnCommentListener((posit, bean, user_id) -> {
                        show("回复功能暂没实现");
                    });
                    recyclerViewHolder.rvComment.notifyDataSetChanged();
                } else {
                    recyclerViewHolder.rvComment.setVisibility(View.GONE);
                }
            } else {
                recyclerViewHolder.llLike.setVisibility(View.GONE);
            }

//        头像显示
            String headUrl = IMAGE_URL + "/head/" + postList.get(position).getMain().getPost().getPostAccount() + ".jpg";
            Glide.with(context)
                    .load(headUrl)
//                    .skipMemoryCache(true)
//                    .signature( new ObjectKey(HEAD_SIG))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .placeholder(R.mipmap.ic_launcher)
                    .fallback(R.drawable.ic_launcher_background)
                    .into(recyclerViewHolder.ivHead);

//        图片显示
            GridLayoutManager layoutManager = new GridLayoutManager(context, 3);
            int imageCount = postList.get(position).getImagesUrls().size();
            if (imageCount == 0) {
                // 没有微博图片
                recyclerViewHolder.rvImages.setVisibility(View.GONE);
            } else {    // 有微博图片
                recyclerViewHolder.rvImages.setVisibility(View.VISIBLE);
                // 动态的指定图片宫格的宽高和RecyclerView的宽度
                // 1张图片 -> 1列
                // 4张图片 -> 2列
                // 其它    -> 3列
                ViewGroup.LayoutParams param = recyclerViewHolder.rvImages.getLayoutParams();
                if (imageCount == 1) {
                    layoutManager.setSpanCount(1);
                    param.width = ViewGroup.LayoutParams.WRAP_CONTENT;
                    param.width = ViewGroup.LayoutParams.WRAP_CONTENT;
                } else if (imageCount == 4) {
                    layoutManager.setSpanCount(2);
                    // 两个图片宫格的宽度
                    param.width = Global.getGridWidth() * 2;
                } else {        // 3列
                    layoutManager.setSpanCount(3);
                    param.width = ViewGroup.LayoutParams.MATCH_PARENT;
                }

                // 刷新图片显示
                recyclerViewHolder.rvImages.setLayoutManager(layoutManager);
                ImagesAdapter adapter = new ImagesAdapter(context, postList.get(position).getImagesUrls());
                recyclerViewHolder.rvImages.setAdapter(adapter);
            }
//            //先判断是否添加过，否则可能会重复添加
//            if (!positions.contains(position)) {
//                positions.add(position);
//            }
        } else if (holder instanceof FootViewHolder) {
            Log.d(TAG, "onBindViewHolder: ViewHolder");
            Log.d(TAG, "onBindViewHolder: position:" + position);
            FootViewHolder footViewHolder = (FootViewHolder) holder;
            switch (loadState) {
                case LOADING:
                    // 正在加载
                    footViewHolder.pbLoading.setVisibility(View.VISIBLE);
                    footViewHolder.tvLoading.setVisibility(View.VISIBLE);
                    footViewHolder.llEnd.setVisibility(View.GONE);
                    break;

                case LOADING_COMPLETE:
                    // 加载完成
                    footViewHolder.pbLoading.setVisibility(View.INVISIBLE);
                    footViewHolder.tvLoading.setVisibility(View.INVISIBLE);
                    footViewHolder.llEnd.setVisibility(View.GONE);
                    break;

                case LOADING_END:
                    // 加载到底
                    footViewHolder.pbLoading.setVisibility(View.GONE);
                    footViewHolder.tvLoading.setVisibility(View.GONE);
                    footViewHolder.llEnd.setVisibility(View.VISIBLE);
                    break;

                default:
                    break;
            }
        }

    }

    //    刷新数据
    public void refreshView(List<Item> postList) {
        this.postList = postList;
        notifyDataSetChanged();
    }

    //    添加数据
    public void addDatas(List<Item> items) {
        int positionStart = postList.size();
        postList.addAll(items);
        int itemCount = postList.size() - positionStart;
        notifyItemRangeInserted(positionStart + 1, itemCount);
    }


    @Override
    public int getItemViewType(int position) {
        // 最后一个item设置为FooterView
        if (position + 1 == getItemCount()) {
            return TYPE_FOOTER;
        } else {
            return TYPE_ITEM;
        }
    }

    /**
     * 设置上拉加载状态
     *
     * @param loadState 0.正在加载 1.加载完成 2.加载到底
     */
    public void setLoadState(int loadState) {
        this.loadState = loadState;
        notifyDataSetChanged();
    }

    private void showLikePopupWindow(View view, int position, ViewHolder recyclerViewHolder) {
        LikePopupWindow likePopupWindow = recyclerViewHolder.likePopupWindow;
        List<Star> list = postList.get(position).getMain().getStars();
        //                判断用户是否已经点赞
        for (Star star : list) {
            isLike = star.getName().equals(NAME) ? 1 : 0;
            if (isLike == 1) {
                break;
            }
        }
        likePopupWindow.setTextView(isLike);
        likePopupWindow.setOnPraiseOrCommentClickListener(new OnPraiseOrCommentClickListener() {
            @Override
            public void onPraiseClick(int position) {
                //调用点赞接口
                getLikeData(position);
                likePopupWindow.dismiss();
            }

            @Override
            public void onCommentClick(int position) {
                llComment.setVisibility(View.VISIBLE);
                etComment.requestFocus();
                etComment.setHint("说点什么");
                KeyboardUtils.showSoftInput(context);
                likePopupWindow.dismiss();
                etComment.setText("");
            }

            @Override
            public void onClickFrendCircleTopBg() {

            }

            @Override
            public void onDeleteItem(String id, int position) {

            }

        }).setTextView(isLike).setCurrentPosition(position);
        if (likePopupWindow.isShowing()) {
            likePopupWindow.dismiss();
        } else {
            likePopupWindow.showPopupWindow(view);
        }
    }

    public void getLikeData(int postion) {
        //                    判断是否已经登录

        if (LOGIN) {
            Handler handler = new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(@NonNull Message msg) {
                    switch (msg.what) {
                        case 200:
                            show("点赞成功");
                            Integer index = (Integer) msg.obj;
                            List<Star> stars = postList.get(index).getMain().getStars();
                            Star star = new Star();
                            star.setName(NAME);
                            stars.add(star);
                            notifyDataSetChanged();
                            break;
                        case 201:
                            Log.d(TAG, "handleMessage: 取消点赞成功");
                            show("取消点赞成功");
                            Integer index1 = (Integer) msg.obj;
                            List<Star> stars1 = postList.get(index1).getMain().getStars();
                            List<Star> likeListBeans1 = new ArrayList<>();
                            Iterator it1 = stars1.iterator();
                            while (it1.hasNext()) {
                                Star info = (Star) it1.next();
                                if (String.valueOf(info.getName()).equals(String.valueOf(NAME))) {
                                    it1.remove();
                                } else {
                                    likeListBeans1.add(info);
                                }
                            }
                            postList.get(index1).getMain().setStars(likeListBeans1);
                            notifyDataSetChanged();
                            break;
                        case 302:
                            Toast.makeText(context, "已经点过赞了", Toast.LENGTH_SHORT).show();
                            break;
                        case 404:
                            Toast.makeText(context, "网络连接失败", Toast.LENGTH_SHORT).show();
                            break;
                        case 500:
                            Toast.makeText(context, "操作失败", Toast.LENGTH_SHORT).show();
                            break;
                        default:
                            System.out.println("返回错误");
                    }
                    return false;
                }
            });
            StarService starService = new StarService();
            starService.pushStar(postList.get(postion).getMain().getPost().getPostId(), handler, isLike, postion);
        }

    }

    public void getComment(ViewHolder recyclerViewHolder, int position) {
        //判断是否登录
        if (LOGIN) {
            //取出评论
            commentStr = etComment.getText().toString().trim();
            //    评论发布
            Handler handler1 = new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(@NonNull Message msg) {
                    switch (msg.what) {
                        case 0:
                            Toast.makeText(context, "成功评论", Toast.LENGTH_SHORT).show();
                            HandlerPosition handlerPosition = (HandlerPosition) msg.obj;
                            int index = handlerPosition.getPosition();
                            Comment comment = (Comment) handlerPosition.getObj();
                            comment.setCmtName(NAME);
                            postList.get(index).getMain().getComments().add(comment);
//                            打印返回的comment对象
                            Log.d(TAG, "handleMessage: " + comment.getCmtName());
                            notifyDataSetChanged();
                            break;
                        case 404:
                            Toast.makeText(context, "没有找到服务器", Toast.LENGTH_SHORT).show();
                            break;
                        case 505:
                            Toast.makeText(context, "评论失败", Toast.LENGTH_SHORT).show();
                            ;
                        default:
                            break;
                    }
                    return false;
                }
            });
            if (TextUtils.isEmpty(commentStr)) {
                Toast.makeText(context, "评论内容不能为空", Toast.LENGTH_SHORT).show();
            } else {
                Comment comment = new Comment();
                comment.setCommentContent(commentStr);
                comment.setCommentAccount(ACCOUNT);
//                打印position
                Log.d(TAG, "getComment: " + position);
                comment.setPostId(postList.get(position).getMain().getPost().getPostId());
                CmtService cmtService = new CmtService();
                cmtService.pushCmt(comment, handler1, position);
            }
        } else {
            Toast.makeText(context, "请先登录", Toast.LENGTH_SHORT).show();
        }
        KeyboardUtils.hideSoftInput((Activity) context);
        llComment.setVisibility(View.GONE);
    }

    //  删除数据
    public void removeData(int position) {
        if (type == POSTMANAGER) {
            CancelOrOkDialog dialog = new CancelOrOkDialog(context, "要删除确认删除?") {
                @Override
                public void ok() {
                    super.ok();
                    Handler handler = new Handler(new Handler.Callback() {
                        @Override
                        public boolean handleMessage(@NonNull Message msg) {
                            closeDialog(context);
                            switch (msg.what) {
                                case 200:
                                    ToastUtils.show("删除成功");
                                    postList.remove(position);
                                    //删除动画
                                    notifyItemRemoved(position);
                                    notifyDataSetChanged();
                                    break;
                                case 505:
                                    ToastUtils.show("删除失败");
                                    break;
                                default:
                            }
                            return false;
                        }
                    });
                    deletePost(postList.get(position).getMain().getPost().getPostId(), handler);
                    dismiss();
                }
            };
            dialog.show();
        } else {
            show("暂时没有实现该功能");
        }

    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public RecyclerView rvImages;
        public View viewLike;
        public LinearLayout llLike;
        public TextView tvUser, tvCnt, tvDate, tvCmt, tvIntro, tvStar, tvCmtName;
        public ImageView ivHead;
        public TabLayout tab;
        public FloatingActionButton btnFlt;
        public TextView tvDelete;
        public ExpandTextView expandTextView;
        public PraiseListView rvLike;
        public CommentsView rvComment;
        public ImageView ivEdit;
        public LikePopupWindow likePopupWindow;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            rvImages = itemView.findViewById(R.id.rv_post_images);
            tvUser = itemView.findViewById(R.id.tv_user);
            tvDate = itemView.findViewById(R.id.tv_date);
            tvCmt = itemView.findViewById(R.id.tv_cmt);
            tvIntro = itemView.findViewById(R.id.tv_user_introduction);
            tvStar = itemView.findViewById(R.id.tv_star);
            tab = itemView.findViewById(R.id.bottom_tab_layout);
            btnFlt = itemView.findViewById(R.id.btn_float);
            ivHead = itemView.findViewById(R.id.iv_head);
            tvDelete = itemView.findViewById(R.id.tv_delete);
            expandTextView = itemView.findViewById(R.id.tv_content);
            rvLike = itemView.findViewById(R.id.rv_like);
            viewLike = itemView.findViewById(R.id.view_like);
            llLike = itemView.findViewById(R.id.ll_like_comment);
            rvComment = itemView.findViewById(R.id.rv_comment);
            ivEdit = itemView.findViewById(R.id.iv_edit);
            likePopupWindow = new LikePopupWindow(itemView.getContext());
        }
    }

    public static class FootViewHolder extends RecyclerView.ViewHolder {

        AVLoadingIndicatorView pbLoading;
        TextView tvLoading;
        LinearLayout llEnd;

        FootViewHolder(View itemView) {
            super(itemView);
            pbLoading = itemView.findViewById(R.id.ld_more);
            tvLoading = itemView.findViewById(R.id.tv_loading);
            llEnd = itemView.findViewById(R.id.ll_end);
        }
    }

    public interface Click {
        void Commend(int position, Comment bean);//回复评论
    }
}
